package com.bw.android.bwgao6week2a;


import android.content.Context;
import android.content.Intent;

import androidx.lifecycle.ViewModelProvider;

import com.bw.android.bwgao6week2a.databinding.ActivityWatchLiveBinding;
import com.bw.android.bwgao6week2a.vm.WatchViewModel;
import com.bw.android.network.ApiService;
import com.bw.android.network.RequestClient;
import com.bw.android.network.bean.LiveListBean;
import com.bw.ch.baselib.BaseBindingActivity;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class WatchLiveActivity extends BaseBindingActivity<ActivityWatchLiveBinding> {
    public static final String RECORD_VIDEO_URI = "live-platform/recordVideo/";
    private LiveListBean.ResultBean mLiveBean;
    private WatchViewModel watchViewModel;
    public static void open(Context context, LiveListBean.ResultBean liveBean) {
        Intent intent = new Intent(context, WatchLiveActivity.class);
        intent.putExtra("data", liveBean);
        context.startActivity(intent);
    }

    @Override
    public int getLayout() {
        return R.layout.activity_watch_live;
    }

    @Override
    protected void initView() {
        mLiveBean = (LiveListBean.ResultBean)this.getIntent().getSerializableExtra("data");
        watchViewModel = new ViewModelProvider(this).get(WatchViewModel.class);
        watchViewModel.setLiveBean(mLiveBean);
        mBinding.setLifecycleOwner(this);
        mBinding.setWatchVm(watchViewModel);
    }

    @Override
    protected void initData() {
        if (mLiveBean.getLiveStatus() == 1) {
            //看直播，需要请求API
            loadLiveData();
        } else {
            // 看录播
            final String videoUrl = ApiService.BASE_URL + RECORD_VIDEO_URI + mLiveBean.getLiveId();
            mBinding.videoPlayer.setUp(videoUrl, true, mLiveBean.getNickName());
            mBinding.videoPlayer.startPlayLogic();
        }
    }

    /***
     * 请求看直播的API
     */
    private void loadLiveData() {
        final String sessionId = AppInstance.getInstance().loginResultBean.getSessionId();
        final int userId = AppInstance.getInstance().getUserId();
        RequestClient.buildService().getWatchLive(userId, sessionId, mLiveBean.getLiveId())
                .subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).subscribe(watchLiveBean -> {
                    String steamUrl = watchLiveBean.getResult().getLiveStreamUrl();
                    String nickName = watchLiveBean.getResult().getNickName();
                    mBinding.videoPlayer.setUp(steamUrl, true, nickName);
                    mBinding.videoPlayer.startPlayLogic();
                });
    }

    @Override
    protected void onDestroy() {
        mBinding.videoPlayer.release();
        super.onDestroy();
    }
}